<template>
  <div class="login-container">
    <div class="login-box">
      <h1 class="title">XXX物联网设备管理平台</h1>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <input type="text" v-model="username" placeholder="用户名" required>
        </div>
        <div class="form-group">
          <input type="password" v-model="password" placeholder="密码" required>
        </div>
        <!-- 错误信息会在这里显示 -->
        <p v-if="error" class="error-message">{{ error }}</p>
        <button type="submit" class="login-button" :disabled="loading">
          {{ loading ? '登录中...' : '登 录' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';

const username = ref('admin');
const password = ref('');
const error = ref('');
const loading = ref(false);

const router = useRouter();
const authStore = useAuthStore();

const handleLogin = async () => {
  loading.value = true;
  error.value = '';
  
  // 【核心修正】直接接收 login action 的返回结果
  const result = await authStore.login({
    username: username.value,
    password: password.value,
  });

  loading.value = false;

  if (result.success) {
    // 登录成功，跳转到仪表盘
    router.push('/dashboard');
  } else {
    // 登录失败，显示从 store 返回的错误信息
    error.value = result.error;
  }
};
</script>

<style scoped>
/* ... 样式保持不变 ... */
.login-container { display: flex; align-items: center; justify-content: center; height: 100vh; background-color: #f0f2f5; }
.login-box { width: 360px; padding: 40px; background: white; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
.title { text-align: center; margin-bottom: 24px; color: #333; }
.form-group { margin-bottom: 20px; }
input { width: 100%; padding: 12px; border: 1px solid #d9d9d9; border-radius: 4px; }
.login-button { width: 100%; padding: 12px; border: none; background-color: #1890ff; color: white; border-radius: 4px; cursor: pointer; }
.error-message { color: red; text-align: center; margin-bottom: 10px; min-height: 1.2em; }
</style>